package com.imooc.business.core.executor;

import com.imooc.business.RuleBusiness;
import com.imooc.business.context.DataContext;
import com.imooc.business.core.executor.calculate.CalculateProcess;
import com.imooc.business.core.executor.collect.CollectCommon;
import com.imooc.business.core.executor.storage.StorageProcess;
import com.imooc.business.core.executor.up.UpDimensionProcess;
import com.imooc.business.domain.Rule;
import com.imooc.module.collect.enums.DimensionEnum;
import com.imooc.module.collect.enums.PeriodEnum;
import com.imooc.module.collect.enums.RuleTypeEnum;
import com.imooc.module.collect.request.ParamsRequest;
import lombok.Setter;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author Tim
 * @Description: 计算采集实现类
 * @Version 1.0
 */
@Setter(onMethod_=@Autowired)
@Component
public class ProducerProcess implements Process{

    private RuleBusiness ruleBusiness;
    private CollectCommon collectCommon;
    private CalculateProcess calculateProcess;
    private StorageProcess storageProcess;
    private UpDimensionProcess upDimensionProcess;

    @Override
    public void doProcess(DataContext context) {
        checkRequest(context);
        initModel(context);
        //做数据采集
        collectCommon.getProcess(context.getCacheModel().getDimension(), context.getCacheModel().getPeriod()).
                collect(context);
        //做计算
        calculateProcess.process(context);
        //做数据存储
        storageProcess.process(context);
        //做维度升级
        upDimensionProcess.up(context);
    }

    /**
     * 初始化计算数据模型
     * @param context
     */
    private void initModel(DataContext context) {
        ParamsRequest request = context.getRequest();
        Rule rule = ruleBusiness.getRule(request.getBusinessId(), request.getRuleTypeEnum().getSourceType());
        context.getCacheModel().
                setRule(rule).
                setDimension(DimensionEnum.parse(request.getDimensionParameter().getDimension())).
                setPeriod(PeriodEnum.parse(request.getPeriodType())).
                setResults(Lists.newArrayList());
    }

    /**
     * 校验参数
     * @param context
     */
    private void checkRequest(DataContext context) {
        context.getRequest().validate();
    }

    @Override
    public boolean support(DataContext context) {
        return RuleTypeEnum.COLLECT.equals(context.getRequest().getRuleTypeEnum());
    }
}
